﻿/* 
Author: MBH
DateAuthored: 8/13/09
*/

//A liteGrid module that will persist the changes to a cell immediately upon modification.
function CellSaveModule() {

	var base = this;

	//Registers for column-bound events, which are used to check for changed cells.
	base.initialize = function(liteGrid, options) {

		base.dataProvider = liteGrid.dataProvider;

		if (!base.dataProvider.saveCell) {
			console.error("This module is only compatible with data providers that expose saveCell.");
			return;
		}

		liteGrid.$el.bind("columnBound", base.columnBound);

		base.keyField = options.rowIdColumn;
	}

	//Callback that is invoked each time a cell is changed.
	base.columnBound = function(event) {
	    var column = event.column;
	    var element = event.element;

	    //See if the element has been edited
	    if (element.hasClass("modified")) {
	        var dataItem = element.parent().data("dataItem");
	        var newValue = dataItem[column.field];
	        var id = dataItem[base.keyField];

	        base.dataProvider.saveCell(id, column.field, newValue,
	        //Success callback
				function(data) {
				    if (data.status !== true) {
				        return;
				    }
				    else {
				        //TODO: Rebind the column to server-side changes?
				        element.removeClass("modified");
				    }
				}
			);
	    }
	}
}